package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/pelletier/go-toml"
)

const (
	configFileName = ".grmconf.toml"
)

type Config struct {
	Registry RegistryConfig `toml:"registry"`
}

type RegistryConfig struct {
	URL string `toml:"url"`
}

func main() {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		fmt.Println("Failed to determine user's home directory:", err)
		os.Exit(1)
	}

	configFilePath := filepath.Join(homeDir, configFileName)

	// Check if config file exists, otherwise create it
	if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
		err := createDefaultConfigFile(configFilePath)
		if err != nil {
			fmt.Println("Failed to create config file:", err)
			os.Exit(1)
		}
	}

	args := os.Args[1:]
	if len(args) == 0 {
		fmt.Println("Please provide a command: set, unset, or setrepo")
		os.Exit(1)
	}

	command := args[0]

	switch command {
	case "set":
		err := enableMirror(configFilePath)
		if err != nil {
			fmt.Println("Failed to enable mirror:", err)
			os.Exit(1)
		}
		fmt.Println("Mirror enabled.")
	case "unset":
		err := disableMirror()
		if err != nil {
			fmt.Println("Failed to disable mirror:", err)
			os.Exit(1)
		}
		fmt.Println("Mirror disabled.")
	case "setrepo":
		if len(args) < 2 {
			fmt.Println("Please provide a repository URL.")
			os.Exit(1)
		}
		err := updateRegistryURL(configFilePath, args[1])
		if err != nil {
			fmt.Println("Failed to update registry URL:", err)
			os.Exit(1)
		}
		fmt.Println("Registry URL updated.")
	default:
		fmt.Println("Invalid command:", command)
		os.Exit(1)
	}
}

func createDefaultConfigFile(filePath string) error {
	defaultConfig := &Config{
		Registry: RegistryConfig{
			URL: "https://githubfast.com/",
		},
	}

	configData, err := toml.Marshal(defaultConfig)
	if err != nil {
		return err
	}

	err = os.WriteFile(filePath, configData, 0o644)
	if err != nil {
		return err
	}

	return nil
}

func enableMirror(configFilePath string) error {
	config, err := loadConfig(configFilePath)
	if err != nil {
		return err
	}

	cmd := exec.Command("git", "config", "--global", "url."+config.Registry.URL+".insteadOf", "https://github.com/")
	err = cmd.Run()
	if err != nil {
		return err
	}

	return nil
}

func disableMirror() error {
	cmd := exec.Command("git", "config", "--global", "--unset-all", "url.https://githubfast.com/.insteadOf")
	err := cmd.Run()
	if err != nil {
		return err
	}

	return nil
}

func updateRegistryURL(configFilePath, newURL string) error {
	config, err := loadConfig(configFilePath)
	if err != nil {
		return err
	}

	config.Registry.URL = newURL

	configData, err := toml.Marshal(config)
	if err != nil {
		return err
	}

	err = os.WriteFile(configFilePath, configData, 0o644)
	if err != nil {
		return err
	}

	return nil
}

func loadConfig(configFilePath string) (*Config, error) {
	config := &Config{}

	configData, err := os.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}

	err = toml.Unmarshal(configData, config)
	if err != nil {
		return nil, err
	}

	return config, nil
}
